package com.gx.smart.building.ui.inspection.viewmodel

import android.app.Application
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.ToastUtils
import com.casic.gx.grpc.common.ComQuery
import com.gx.smart.base.livedata.SingleLiveEvent
import com.gx.smart.building.PlanTaskApiService
import com.gx.smart.building.admin.SysRegionApiService
import com.gx.smart.building.ui.common.viewmodel.CommonViewModel
import com.gx.smart.building.ui.inspection.event.FinishedQuantityEvent
import com.gx.smart.building.ui.inspection.event.InspectionListEvent
import com.gx.smart.building.ui.inspection.event.TaskInCompleteListEvent
import com.gx.smart.building.ui.inspection.event.UnfinishedQuantityEvent
import com.gx.smart.lib.http.api.RetrofitManager
import com.gx.smart.lib.http.api.asynctask.CallBack
import com.gx.smart.lib.http.api.config.ApiConfig
import com.gx.smart.lib.http.api.response.PlanTask
import com.gx.smart.lib.http.api.response.PlanTaskAsset
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.AddPlanTaskEventResp
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.HandleTaskResp
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.QueryPlanTaskAssetDetailResp
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.QueryPlanTaskAssetListResp
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.QueryPlanTaskListResp
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetDto
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetFileDto
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskAssetItemResultDto
import com.huishi.gx.ib.grpc.lib.ib.app.plantask.v1.dto.PlanTaskDto
import com.huishi.gx.ib.grpc.lib.sysuser.sysregionapi.SysRegionDto
import com.huishi.gx.ib.grpc.lib.sysuser.sysregionapi.SysRegionQueryResponse
import com.orhanobut.logger.Logger
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 *@author: xiaosy
 *时间: 2022/3/22
 *@Description: java类作用描述
 *@Version: 1.0
 **/
class InspectionViewModel(application: Application) : CommonViewModel(application) {
    private val quantity: SingleLiveEvent<List<Long>> = SingleLiveEvent()
    private val taskQuantity: MutableLiveData<List<Long>> = MutableLiveData()

    val detail: MutableLiveData<PlanTaskAsset> = MutableLiveData()
    val detailFileList: MutableLiveData<List<PlanTaskAssetFileDto>> = MutableLiveData()
    val detailResultList: MutableLiveData<List<PlanTaskAssetItemResultDto>> =
        MutableLiveData()

    private val handleSuccess: MutableLiveData<Boolean> = MutableLiveData()
    private val regionList: MutableLiveData<List<SysRegionDto>> = MutableLiveData()

    private val forwardSuccess: MutableLiveData<Boolean> = MutableLiveData()

    /**
     * 移动端计划列表
     */
    fun queryPlanTaskList(
        currentPage: Int,
        status: Int,
        taskCode: String,
        handleTimeStart: Long,
        handleTimeEnd: Long,
    ): LiveData<List<PlanTask>> {
        val list: MutableLiveData<List<PlanTask>> = MutableLiveData()
        val comQuery = ComQuery.newBuilder()
            .setPage(currentPage)
            .setPageSize(10)
            .build()

        RetrofitManager.getInstance().planTaskApiService.queryPlanTaskList().enqueue(object: Callback<com.gx.smart.lib.http.api.response.QueryPlanTaskListResp> {
            override fun onResponse(
                call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskListResp>,
                response: Response<com.gx.smart.lib.http.api.response.QueryPlanTaskListResp>
            ) {
                val result = response.body()
                if (result == null) {
                    ToastUtils.showLong("服务器超时")
                    return
                }
                val comResp = result.comResp
                if (comResp.code == 100) {
                    list.value = result.planTaskDto
                    //状态：1-已完成，2-未完成
                    when (status) {
                        2 -> EventBus.getDefault()
                            .post(UnfinishedQuantityEvent(10))

                        1 -> EventBus.getDefault()
                            .post(FinishedQuantityEvent(20))
                    }
                } else {
                    ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
                }
            }

            override fun onFailure(call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskListResp>, t: Throwable) {
                ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
            }
        })
        return list
    }


    /**
     * 移动端任务列表
     */
    fun queryPlanTaskAssetList(
        currentPage: Int,
        status: Int,
        plantTaskId: String,
        assetName: String,
        areaId: String
    ): LiveData<List<PlanTaskAsset>> {
        val taskList: MutableLiveData<List<PlanTaskAsset>> = MutableLiveData()
        val comQuery = ComQuery.newBuilder()
            .setPage(currentPage)
            .setPageSize(10)
            .build()

        RetrofitManager.getInstance().planTaskApiService.queryAppPlanTaskAssetList().enqueue(object : Callback<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetListResp> {
            override fun onResponse(
                call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetListResp>,
                response: Response<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetListResp>
            ) {
                val result = response.body()
                if (result == null) {
                    ToastUtils.showLong("服务器超时")
                    return
                }
                val comResp = result.comResp
                if (comResp.code == 100) {
                    taskList.value = result.planTaskAssetDto
                    //状态：1-已完成，2-未完成
                    when (status) {
                        2 -> EventBus.getDefault()
                            .post(UnfinishedQuantityEvent(10))

                        1 -> EventBus.getDefault()
                            .post(FinishedQuantityEvent(20))
                    }
                } else {
                    ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
                }
            }

            override fun onFailure(
                call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetListResp>,
                t: Throwable
            ) {
                Logger.e(t,"error")
                ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
            }

        })

        return taskList
    }

    /**
     * 移动端任务详情
     */
    fun queryPlanTaskAssetDetail(planTaskId: String, assetId: String) {
        RetrofitManager.getInstance().planTaskApiService.queryAppPlanTaskAssetDetail().enqueue(object : Callback<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetDetailResp> {
            override fun onResponse(
                call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetDetailResp>,
                response: Response<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetDetailResp>
            ) {
                val result = response.body()
                if (result == null) {
                    ToastUtils.showLong("服务器超时")
                    return
                }
                val comResp = result.comResp
                if (comResp.code == 100) {
                    //计划任务列表
                    detail.value = result.planTaskAssetDto
                    //处理结果文件
//                    detailFileList.value = result.taskAssetFileDtoList
//                    detailResultList.value = result.taskAssetItemResultDtoList
                } else {
                    ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
                }
            }

            override fun onFailure(
                call: Call<com.gx.smart.lib.http.api.response.QueryPlanTaskAssetDetailResp>,
                t: Throwable
            ) {
                ToastUtils.showLong(ApiConfig.SERVER_ERROR_MESSAGE)
            }

        })
    }

    /**
     * 移动端处理任务
     */
    fun handleTask(
        planTaskAssetDto: PlanTaskAssetDto,
        planTaskAssetFileDto: List<PlanTaskAssetFileDto>,
        planTaskAssetItemResultDto: List<PlanTaskAssetItemResultDto>
    ): LiveData<Boolean> {
        PlanTaskApiService.getInstance().handleTask(planTaskAssetDto,
            planTaskAssetFileDto,
            planTaskAssetItemResultDto,
            object : CallBack<HandleTaskResp>() {
                override fun callBack(result: HandleTaskResp?) {
                    if (result == null) {
                        ToastUtils.showLong("服务器超时")
                        handleSuccess.value = false
                        return
                    }
                    val comResp = result.comResp
                    if (comResp.code == 100) {
                        handleSuccess.value = true
                    } else {
                        handleServiceException(comResp)
                        handleSuccess.value = false
                    }
                }
            })
        return handleSuccess
    }

    //查询
    fun sysRegionQuery(): LiveData<List<SysRegionDto>> {
        SysRegionApiService.getInstance()
            .sysRegionQuery(object : CallBack<SysRegionQueryResponse>() {
                override fun callBack(result: SysRegionQueryResponse?) {
                    if (result == null) {
                        ToastUtils.showLong("服务器超时")
                        return
                    }
                    val comResp = result.comResp
                    if (comResp.code == 100) {
                        regionList.value = result.contentList
                    } else {
                        handleServiceException(comResp)
                    }
                }
            })
        return regionList
    }

    //转派
    fun forwardTask(
        planTaskId: String,
        opinion: String,
        assignUserName: String,
        userId: String
    ): LiveData<Boolean> {
        PlanTaskApiService.getInstance().forwardTask(
            planTaskId,
            opinion,
            assignUserName,
            userId,
            object : CallBack<AddPlanTaskEventResp>() {
                override fun callBack(result: AddPlanTaskEventResp?) {
                    if (result == null) {
                        ToastUtils.showLong("服务器超时")
                        return
                    }
                    val comResp = result.comResp
                    if (comResp.code == 100) {
                        forwardSuccess.value = true
                    } else {
                        handleServiceException(comResp)
                    }
                }
            })
        return forwardSuccess
    }
}